package com.qyhl.webtv.module_user.share;


import android.os.Bundle;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.qyhl.webtv.basiclib.utils.network.callback.SimpleCallBack;
import com.qyhl.webtv.basiclib.utils.network.exception.ApiException;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.entity.user.ShareFriendListBean;
import com.qyhl.webtv.commonlib.entity.user.UserInfoBean;
import com.qyhl.webtv.module_user.R;
import com.qyhl.webtv.module_user.R2;
import com.qyhl.webtv.module_user.common.UserUrl;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * A simple {@link Fragment} subclass.
 */
public class FriendListFragment extends BaseFragment {
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout mLoadingLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.friendNum)
    TextView friendNum;

    private ArrayList<UserInfoBean> list;
    private int page = 1;
    private CommonAdapter<UserInfoBean> commonAdapter;

    public static FriendListFragment newInstance() {
        FriendListFragment fragment = new FriendListFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.login_fragment_friend_list, container, false);
    }

    @Override
    protected void create() {
        list = new ArrayList<>();
    }

    @Override
    protected void setListener() {

    }

    @Override
    protected void onFirstVisible() {
        SpanUtils spanUtils = new SpanUtils(getContext());
        spanUtils.append("你已经邀请了")
                .append("0").setSpans(new TextAppearanceSpan(getActivity(), R.style.login_friend_list))
                .append("位好友");
        friendNum.setText(spanUtils.create());
        mLoadingLayout.setStatus(LoadingLayout.Loading);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        recyclerView.setAdapter(commonAdapter = new CommonAdapter<UserInfoBean>(getContext(), R.layout.login_share_friendlist_layout, list) {
            @Override
            protected void convert(ViewHolder viewHolder, UserInfoBean bean, int pos) {
                viewHolder.setText(R.id.time, bean.getGmtModified());
                viewHolder.setText(R.id.name, bean.getNickName());
                viewHolder.setText(R.id.phone, StringUtils.encodePhoneNum(bean.getUsername()));
                ImageView img = viewHolder.getView(R.id.img);
                Glide.with(getActivity())
                        .load(bean.getLogo())
                        .apply(new RequestOptions()
                                .centerCrop()
                                .error(R.drawable.comment_head_default)
                                .transform(new GlideCircleTransform(getContext())))
                        .into(img);
            }
        });

        refresh.setEnableLoadMore(true);
        refresh.setEnableRefresh(true);
        //刷新中禁止操作
        refresh.setDisableContentWhenRefresh(true);
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        //下拉刷新
        refresh.setOnRefreshListener(refreshlayout -> {
            page = 1;
            getData();
            refresh.setEnableLoadMore(true);
        });
        //加载更多
        refresh.setOnLoadMoreListener(refreshlayout -> getData());
        //重刷
        mLoadingLayout.setOnReloadListener(view -> {
            page = 1;
            getData();
            mLoadingLayout.setStatus(LoadingLayout.Loading);
            refresh.setEnableLoadMore(true);
        });

        getData();
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    private void getData() {
        String code = CommonUtils.getInstance().getCode();

        EasyHttp.get(UserUrl.GET_USER_INVITECODELIST)
                .params("inviteCode", code)
                .params("page", String.valueOf(page))
                .execute(new SimpleCallBack<ShareFriendListBean>() {
                    @Override
                    public void onError(ApiException e) {
                        error("获取数据失败");
                    }

                    @Override
                    public void onSuccess(ShareFriendListBean shareFriendListBean) {
                        success(shareFriendListBean);
                    }
                });

    }


    private void success(ShareFriendListBean data) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            refresh.finishRefresh();
            refresh.finishLoadMore();
            mLoadingLayout.setStatus(LoadingLayout.Success);
            if (data != null) {
                List<UserInfoBean> topicNews = data.getUserList();
                if (topicNews == null || topicNews.size() == 0) {
                    if (page == 1) {
                        mLoadingLayout.setEmptyText("暂无内容");
                        mLoadingLayout.setEmptyImage(R.drawable.empty_comment);
                        mLoadingLayout.setStatus(LoadingLayout.Empty);
                    } else {
                        refresh.setEnableLoadMore(false);
                        Toasty.normal(getContext(), "没有更多啦！").show();
                    }
                } else {
                    //判断两个page是否相等，防止数据重复
//                    if (page == data.getPage()) {
                    SpanUtils spanUtils = new SpanUtils(getContext());
                    spanUtils.append("你已经邀请了")
                            .append(String.valueOf(data.getCount())).setSpans(new TextAppearanceSpan(getActivity(), R.style.login_friend_list))
                            .append("位好友");
                    friendNum.setText(spanUtils.create());

                    if (page == 1) {
                        list.clear();
                    }
                    list.addAll(topicNews);
                    commonAdapter.notifyDataSetChanged();
                    Toasty.normal(getContext(), "加载成功！").show();
                    page++;
//                    }
                }
            } else {
                if (page == 1) {
                    mLoadingLayout.setEmptyText("暂无内容");
                    mLoadingLayout.setEmptyImage(R.drawable.empty_comment);
                    mLoadingLayout.setStatus(LoadingLayout.Empty);
                }
            }
        }
    }

    private void error(String msg) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            refresh.finishRefresh();
            refresh.finishLoadMore();
            if (page == 1) {
                mLoadingLayout.setErrorText(msg);
                mLoadingLayout.setErrorImage(R.drawable.error_content);
                mLoadingLayout.setStatus(LoadingLayout.Error);
            } else {
                Toasty.normal(getContext(), msg).show();
            }
        }
    }
}
